package com.library.system.modules.notice.task;

import cn.hutool.core.collection.CollUtil;
import com.library.common.enums.AuditStatusEnum;
import com.library.system.modules.notice.entity.Notice;
import com.library.system.modules.notice.service.NoticeService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度器
 *
 * @author: xyh
 * @create: 2023-06-02
 **/
@Log4j2
@Component
public class NoticeScheduler {

    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Resource
    private NoticeService noticeService;

    public static class NoticeTaskSender implements Runnable {
        private final Notice notice;
        private final NoticeService noticeService;

        public NoticeTaskSender(Notice notice, NoticeService noticeService) {
            this.notice = notice;
            this.noticeService = noticeService;
        }

        @Override
        public void run() {
            // 到了发布时间，进行发布处理
            Notice nc = noticeService.getById(notice.getId());
            if (AuditStatusEnum.TIME_SEND.getCode().equals(nc.getNoticeStatus())) {
                nc.setNoticeStatus(AuditStatusEnum.SEND_SUCCESS.getCode());
            } else {
                nc.setNoticeStatus(AuditStatusEnum.SEND_FAIL.getCode());
                nc.setFinishTime(LocalDateTime.now());
                nc.setResult("审核超时或审核失败");
            }
            noticeService.updateById(nc);
        }
    }

    @PostConstruct
    public void scheduleArticle() {
        //查询状态为定时发送状态的公告列表
        List<Notice> noticeSendTimes = noticeService.getNoticeSendTime();
        try {
            if (CollUtil.isNotEmpty(noticeSendTimes)) {
                noticeSendTimes.forEach(s -> {
                    threadPoolTaskScheduler.schedule(new NoticeTaskSender(s, noticeService), Date.from(s.getSendTime().atZone(ZoneId.systemDefault()).toInstant()));
                });
            }
            log.info("定时发送状态的公告列表加入任务调度加载完成！");
        } catch (Exception e) {
            log.error("定时发送状态的公告加入任务调度加载失败：", e);
        }
    }

}
